<?php

namespace app\admin\controller\project;

use app\common\controller\Backend;

class Coupon extends Backend
{
    /**
     * 当前控制器下的一个模型属性
     */
    protected $model = null;
    protected $relationSearch = true;

    // 初始化
    public function __construct()
    {
        parent::__construct();
        // 引入的模型
        $this->CouponModel = model('Coupon.Coupon');
        $this->ReceiveModel = model('Coupon.Receive');

        $statusList=[
            '0' => '已失效',
            '1' => '有效',
        ];
        $ReceiveStatusList=[
            '0' => '未使用',
            '1' => '已使用',
            '-1' => '已失效',
        ];
        $this->assign([
            'statusList'=>$statusList,
            'ReceiveStatusList'=>$ReceiveStatusList,
        ]);
        
    }
    public function index()
    {
        if ($this->request->isAjax()) 
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->CouponModel
                ->where($where)
                ->order($sort, 'asc')
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->CouponModel
                ->where($where)
                ->order($sort, 'asc')
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->CouponModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    // 添加
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');
            // 转换时间格式
            $params['createtime']=strtotime($params['createtime']);
            $params['endtime']=strtotime($params['endtime']);
            // let data=new Date();
            // halt($params);
            $result=$this->CouponModel->validate('commmo/Project/Coupon')->save($params);
            if($result === FALSE)
            {
                $this->error($this->CouponModel->getError());
                exit;
            }
            $this->success();
            exit;
        }
        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->CouponModel->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }
        // halt($row->toArray());
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // 转换时间格式
            $params['createtime']=strtotime($params['createtime']);
            $params['endtime']=strtotime($params['endtime']);
            $params['id'] = $ids;
            // halt($params);

            // 查询领取优惠劵数据
            $receive=$this->ReceiveModel->where(['cid'=>$ids])->select();

            // 优惠劵表状态改变为已失效，领取优惠劵表的状态随之改变为已失效
            if($receive)
            {
                foreach($receive as $item)
                {
                    if($item['status'] != '1' && $params['status'] == '0'  )
                    {
                        $OrderData=[
                            'id'=>$item['id'],
                            'status'=>'-1'
                        ];
                    }
                    else if($item['status'] != '1' && $params['status'] == '1'  )
                    {
                        $OrderData=[
                            'id'=>$item['id'],
                            'status'=>'0'
                        ];
                    }else
                    {
                        break;
                    }
                    // var_dump($OrderData);
                    $OrderStatus=$this->ReceiveModel->isUpdate(true)->save($OrderData);
                    if($OrderStatus === FALSE)
                    {
                        $this->error('更新领取优惠劵状态失败');
                        exit;
                    }
                }
            }
            // exit;
            $result = $this->CouponModel->validate("common/Project/Coupon")->isUpdate(true)->save($params);
            if ($result === FALSE) {
                $this->error($this->CouponModel->getError());
                exit;
            }
            $this->success();
            exit;
        }
        $this->assign("row", $row);
        return $this->view->fetch();
    }

    // 删除
    public function del($ids = null)
    {
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->CouponModel->column('id');

        $ReceiveList=[];
        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error(__("没有找到该优惠劵活动"));
                exit;
            }
            $receive=$this->ReceiveModel->where(['cid'=>$item])->column('id');
            $ReceiveList=array_merge($receive,$ReceiveList);
        }

        // 有领取的优惠劵
        if($ReceiveList)
        {
            $ReceiveStatus=$this->ReceiveModel->destroy($ReceiveList);
            if($ReceiveStatus === FALSE)
            {
                $this->error('删除领取的优惠劵失败');
                exit;
            }
        }
        
        $result = $this->CouponModel->destroy($ids);
        if ($result === FALSE) {
            $this->error($this->CouponModel->getError());
            exit;
        }
        $this->success();
        exit;
    }

    // 查看领取优惠劵的详情
    public function receive($ids = null)
    {
        // halt($ids);
        if ($this->request->isAjax()) 
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wherenew=[
                'cid'=>$ids
            ];
            $total = $this->ReceiveModel
                ->with(['business'])
                ->where($where)
                ->where($wherenew)
                ->order($sort, 'asc')
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->ReceiveModel
                ->with(['business'])
                ->where($where)
                ->where($wherenew)
                ->order($sort, 'asc')
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->OrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
}